// Learn cc.Class:
//  - [Chinese] https://docs.cocos.com/creator/manual/zh/scripting/class.html
//  - [English] http://docs.cocos2d-x.org/creator/manual/en/scripting/class.html
// Learn Attribute:
//  - [Chinese] https://docs.cocos.com/creator/manual/zh/scripting/reference/attributes.html
//  - [English] http://docs.cocos2d-x.org/creator/manual/en/scripting/reference/attributes.html
// Learn life-cycle callbacks:
//  - [Chinese] https://docs.cocos.com/creator/manual/zh/scripting/life-cycle-callbacks.html
//  - [English] https://www.cocos2d-x.org/docs/creator/manual/en/scripting/life-cycle-callbacks.html

var curMod = cc.Class({
    extends: cc.Component,

    properties: {
        // foo: {
        //     // ATTRIBUTES:
        //     default: null,        // The default value will be used only when the component attaching
        //                           // to a node for the first time
        //     type: cc.SpriteFrame, // optional, default is typeof default
        //     serializable: true,   // optional, default is true
        // },
        // bar: {
        //     get () {
        //         return this._bar;
        //     },
        //     set (value) {
        //         this._bar = value;
        //     }
        // },
    },

    statics: {
        _instance: null,
        InterstitialAdId: '7a531f4336e642620e10c7c9f009e7a2',
        RewardedVideoAdId: ['62c90b649c27dddf2817a3415cc36304', '0b62a8e298bc4aa64a859f72e1248760', 'e87a2d6e197d9cb593dedc47ec2a958e', '42721fd340bd4262e5ea6ea38d258c6a', '1f002aef690eee1f4bcf69d92a802332', '3335b1a36cdb65adb516a45a5eabcf6d'],
        BannerIds: ['0ba8e3c2f10b8e1577c4c9668f0b7e19', '30b6187d00f2ba0cecfb02f4ba5d0b5f', '1e7c36c5d57fa40acc68b848076d9da9', '624c71eacd80cdf422ea15de70d854c9', '459ce86621e60c6ffa9db1e7d4ce6a0b', '0c94b66c464fca401100528d5483b69d', '912f94ab25b8d7c51ef39eb5dcb2c0ef', '6c6b43a83ed6ff8911c0558dc08ea376', '75f03ebd095941f92d4456a388458060'], //, 'adunit-905904089942c58e'],
        AppBoxId: "69972a8a54610f1a6e73e6c8ed35fd43",
        ShareTitle: '看过许多美景——身边依然还是你',
        //ShareImgId: '5JWEBFBdTHiZ5EcslmutbA==', // 通过 MP 系统审核的图片编号
        //ShareImgUrl: 'https://mmocgame.qpic.cn/wechatgame/3gfJUsiaHCx28sibf4QvxkWEwK6UicbQricJn4M7ia9OoUIPaDXXn1tib6eSZWtpu7hOGz/0',

        _wxUserInfo: {},
        _systemInfo: {},

        Instance() {
            return curMod._instance;
        },
        GetInfo() {
            return curMod._wxUserInfo;
        },
    },

    onLoad() {
        console.log('vivo onload, curMod._instance=', curMod._instance);
        if (curMod._instance) {
            return;
        }
        curMod._instance = this;

        if (require('GameMgr').Instance().ApiType !== 5) {
            return;
        }
        this._bannerAd = null;
        this._intersitialAd = null;
        this._rewardedVideoAd = null;
        //...
        this.setLogin();//用户登录，获取用户信息
        this.createBannerAds();
        this.SGP = require("sg.es5");
        this.SGP.plugin.Service.init({ appId: "1110268371" }, (data) => {
            console.log("init data:" + JSON.stringify(data));
        });
        this.AppBoxCreat();
    },

    start() {
    },

    //显示
    CreatAppBox() {
        if (require('GameMgr').Instance().ApiType !== 5) {
            return;
        }
        if (this.appbox) {
            this.appbox.show();
        }
        else {
            this.AppBoxCreat();
        }
        return;
        this.SGP.plugin.Service.platform.navigateToMiniProgram({
            appId: "1110268371",
            pkgName: "shuangzitiao", //oppo必须，其他平台忽略
            path: "",
            extraData: {},
            callback: (success, code, msg) => {
                console.log("navigateToMiniProgram", success + "," + code + "," + msg);
            }
        });
    },

    AppBoxCreat() {
        this.appbox = qq.createAppBox({
            adUnitId: curMod.AppBoxId,
        });
        this.appbox.load();
        //appbox.onError(function (res) {
        //    console.log('appbox, ', res);
        //});
    },

    // update (dt) {},
    //分享
    shareAppMessage() {
        console.log("qq3", require('GameMgr').Instance().ApiType);
        if (require('GameMgr').Instance().ApiType !== 5) {
            return;
        }
        qq.showShareMenu({
            showShareItems: ['qq', 'qzone', 'wechatFriends', 'wechatMoment']
        })
        qq.aldShareAppMessage({
            title: curMod.ShareTitle,
            shareAppType: "qq",
            success() {
                console.log("分享成功");
                require('GameMgr').Instance().setDaily(5);
                require('GameMgr').onWxShow(1001);
            },
            fail() {
                console.log("分享失败");
                require('GameMgr').Instance().showTip("取消分享，获取奖励失败", 0, "取消", "确定", function () {
                }, function () { return; });
            },
            Component() {

            },
        });
        qq.aldOnShareAppMessage(() => ({
            title: curMod.ShareTitle,
        }));
        /*
        this.SGP.plugin.Service.platform.shareAppMessage({
            title: curMod.ShareTitle,
        });*/
    },

    //显示插屏广告
    showInterstitialAd() {
        console.log("qq2");
        if (require('GameMgr').Instance().ApiType !== 5) {
            return;
        }
        let interstitialAd = qq.createInterstitialAd({
            adUnitId: curMod.InterstitialAdId
        });
        interstitialAd.load();
        interstitialAd.onLoad(() => {
            interstitialAd.show();
        });

        interstitialAd.onError(err => {
            console.log("插屏广告展示失败", err);
            console.log(JSON.stringify(err));
        })
    },

    //显示视频广告
    showRewardedVideoAd(index) {
        console.log("qq1");
        if (require('GameMgr').Instance().ApiType !== 5) {
            return;
        }
        console.log("激励广告加载", index);
        let rewardedAd;
        rewardedAd = qq.createRewardedVideoAd({
            adUnitId: curMod.RewardedVideoAdId[index]
        });

        rewardedAd.load();

        rewardedAd.show();

        rewardedAd.onLoad(() => {
        })

        rewardedAd.onError(err => {
            console.log("激励广告展示失败")
            console.log(JSON.stringify(err));
            //require('GameMgr').Instance().showTip(JSON.stringify(err.data.errMsg) + "\n请稍后再试", 0, "取消", "确定", function () {
            //}, function () { return; });
        })

        rewardedAd.onClose(res => {
            if (res && res.isEnded) {
                console.log("正常播放结束，可以下发游戏奖励");
                require('GameMgr').Instance().ShowADrewords();
                require('GameMgr').Instance().setDaily(2);

            } else {
                console.log("播放中途退出，不下发游戏奖励");
                require('GameMgr').Instance().showTip("中途退出，获取奖励失败", 0, "取消", "确定", function () {
                }, function () { });
            }
        });
    },


    //显示底部广告
    showBannerAd(index) {
        if (require('GameMgr').Instance().ApiType !== 5) {
            return;
        }
        if (!this._bannerAds) {
            this.createBannerAds();
            return;
        }
        if (this._bannerAds[index]) {
            console.log("this._bannerAds", this._bannerAds[index])
            this._bannerAds[index].show();
        }
    },


    createBannerAds() {
        let sysInfo = window.wx.getSystemInfoSync();
        //获取微信界面大小
        let width = sysInfo.screenWidth;
        let height = sysInfo.screenHeight;
        let bannerHeight = height * 0.2;
        let bannerWidth = width * 0.8;
        console.log("****************", cc.winSize);
        this._bannerAds = [];
        var length = curMod.BannerIds.length;
        for (let i = 0; i < length; i++) {
            let banner = qq.createBannerAd({
                adUnitId: curMod.BannerIds[i],
                style: {
                    height: bannerHeight,
                    width: bannerWidth,
                    left: (width / 2 - bannerWidth / 2),
                    top: (height - bannerHeight / 2),
                }
            });
            banner.onLoad(() => {
                this._bannerAds[i] = banner;
            })
            banner.onError(function (res) {
                console.log('banner, ', res);
            });
        }
    },

    //隐藏所有底部广告
    hideBannerAds() {
        if (require('GameMgr').Instance().ApiType !== 5) {
            return;
        }
        if (!this._bannerAds) {
            return;
        }
        if (this._bannerAds && this._bannerAds.length != null) {
            if (this._bannerAds.length > 0) {
                for (var i = 0; i < this._bannerAds.length; i++) {
                    if (this._bannerAds && this._bannerAds[i]) {
                        this._bannerAds[i].hide();
                    }
                }
            }
        }
    },


    wxGameStart(id) {
        if (require('GameMgr').Instance().ApiType !== 5) {
            return;
        }
        var Id = parseInt(id / 1000) + "." + (id % 1000);
        cc.log(Id);
        if (!window.wx) {
            return;
        }
        var Id = parseInt(id / 1000) + "." + (id % 1000);
        cc.log(Id);
        var stagename = "第" + parseInt(id / 1000) + "-" + (id % 1000) + "关";
        wx.aldStage.onStart({
            stageId: Id,     //关卡ID 该字段必传
            stageName: stagename, //关卡名称  该字段必传
            //userId: "06_bmjrPtlm6_2sgVt7hMZOPfL2M" //用户ID 可选
        })
    },

    wxGameING(id, number) {
        if (require('GameMgr').Instance().ApiType !== 5) {
            return;
        }
        // 在关卡中使用道具
        var Id = parseInt(id / 1000) + "." + (id % 1000);
        var stagename = "第" + parseInt(id / 1000) + "." + (id % 1000) + "关";
        var msg = "";
        if (number === 1) {
            msg = "吸金币";
        }
        else if (number === 2) {
            msg = "二段跳";
        }
        wx.aldStage.onRunning({
            stageId: Id,
            stageName: stagename,
            //userId: "123456",
            event: "tools",
            params: {
                itemName: msg,
            }
        });
    },

    wxGameOver(id, state) {
        //关卡完成
        if (require('GameMgr').Instance().ApiType !== 5) {
            return;
        }
        var Id = parseInt(id / 1000) + "." + (id % 1000);
        var stagename = "第" + parseInt(id / 1000) + "." + (id % 1000) + "关";
        var complete = "";
        if (state === 0) {
            complete = "死亡";
            state = "fail";
        }
        else if (state === 1) {
            complete = "复活";
            state = "fail";
        } else if (state === 2) {
            complete = "通关";
            state = "complete";
        } else if (state === 3) {
            complete = "重新开始";
            state = "fail";
        }
        wx.aldStage.onEnd({
            stageId: Id,    //关卡ID 该字段必传
            stageName: stagename, //关卡名称  该字段必传
            //userId: "06_bmjrPtlm6_2sgVt7hMZOPfL2M",  //用户ID 可选
            event: state,   //关卡完成  关卡进行中，用户触发的操作    该字段必传
            params: {
                desc: complete,  //描述
            }
        })
    },


    setLogin() {
        var id = require('GameMgr').Instance().ApiType;
        console.log("渠道ID：" + id);

        if (id === 5) {
            var self = this;
            qq.login({
                success(res) {
                    console.log(res);
                    console.log(JSON.stringify(res));
                    if (res.code) {
                        require('GameMgr').Instance().sendData("login", { "code": res.code, "channelId": id }, function (data) {
                            if (data.code === 0) {
                                console.log("返回数据", data);
                                require('GameMgr').Instance().setLogin(data.uid, data.token, data);
                                self.getQQInfo();
                            }
                            else {
                                console.log("连接失败", data);
                                let self1 = self;
                                require('GameMgr').Instance().showTip("网络连接失败\n请稍后重试", 2, "取消", "确定", function () {
                                    cc.director.loadScene('LoadScene');
                                    return;
                                }, function () {
                                    self1.setLogin();
                                    return;
                                });
                                return;
                            }
                        });
                    } else {
                        console.log('登录失败！' + res.errMsg)
                    }
                },
                fail() {
                    // session_key 已经失效，需要重新执行登录流程
                    self.setLogin() // 重新登录
                },
            });
            qq.checkSession({
                success() {
                    // session_key 未过期，并且在本生命周期一直有效
                },
                fail() {
                    let self1 = self;
                    require('GameMgr').Instance().showTip("连接中断，请重试", 2, "取消", "确定", function () {
                        self1.setLogin();
                        return;
                    }, function () {
                        self1.setLogin();
                        return;
                    });
                }
            })
        }
    },

    getQQInfo() {
        //获取登录信息
        qq.getSetting({
            success(res) {
                let sysInfo = window.wx.getSystemInfoSync();
                //获取微信界面大小
                let width = sysInfo.screenWidth;
                let height = sysInfo.screenHeight;
                if (res.authSetting['scope.userInfo']) {
                    // 已经授权，可以直接调用 getUserInfo 获取头像昵称
                    qq.getUserInfo({
                        success(res) {
                            console.log('当前用户信息: ' + JSON.stringify(res));
                            curMod._wxUserInfo = res.userInfo;
                            var imgurl = curMod._wxUserInfo.avatarUrl + "?aaa=aa.jpg";
                            require('GameMgr').Instance().setplUrl(imgurl);
                            var name = curMod._wxUserInfo.nickName;
                            require('GameMgr').Instance().SetName(name);
                        }
                    })
                }
                else {
                    let button = window.wx.createUserInfoButton({
                        type: 'text',
                        text: '',
                        style: {
                            left: 0,
                            top: 0,
                            width: width,
                            height: height,
                            backgroundColor: '#00000000',//最后两位为透明度
                            color: '#ffffff',
                            fontSize: 20,
                            textAlign: "center",
                            lineHeight: height,
                        }
                    });
                    button.onTap((res) => {
                        console.log('当前用户信息: ' + JSON.stringify(res));
                        curMod._wxUserInfo = res.userInfo;
                        var imgurl = curMod._wxUserInfo.avatarUrl + "?aaa=aa.jpg";
                        require('GameMgr').Instance().setplUrl(imgurl);
                        var name = curMod._wxUserInfo.nickName;
                        require('GameMgr').Instance().SetName(name);
                        button.destroy();
                    })
                }
            }
        });
    },

    printInfo(res) {
        // console.log('设备品牌:', res.brand)
        // console.log('设备型号:', res.model)
        // console.log('设备像素比:', res.pixelRatio)
        // console.log('屏幕宽度:', res.windowWidth)
        // console.log('屏幕高度:', res.windowHeight)
        // console.log('状态栏的高度:', res.statusBarHeight)
        // console.log('微信设置的语言:', res.language)
        // console.log('微信版本号:', res.version)
        // console.log('操作系统及版本:', res.system)
        // console.log('客户端平台:', res.platform)
        // console.log('用户字体大小:', res.fontSizeSetting)
        // console.log('客户端基础库版本 :', res.SDKVersion)
        // console.log('设备性能等级:', res.benchmarkLevel)
        if (res.system.indexOf('Android') != -1) {
            curMod._isAndroid = true;
        }
    },
});
